﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kotonoha.Server.Utils;
using NHibernate;
using NHibernate.Cfg;

namespace Kotonoha.Server.Core.Utils {
    public class HibernateUtil {
        private static HibernateUtil instance;
        public static HibernateUtil Instance {
            get {
                lock (typeof(HibernateUtil)) {
                    if (instance == null) {
                        instance = new HibernateUtil();
                    }
                    return instance;
                }
            }
        }

        private ISessionFactory factory;

        private HibernateUtil() {
            Configuration cfg = new Configuration();
            cfg.Configure("hibernate.cfg.xml");
            cfg.SetProperty("connection.connection_string", string.Format("Data Source={0}", PathUtil.DB_PATH));
            cfg.AddAssembly("Kotonoha");
            factory = cfg.BuildSessionFactory();
        }

        public static void startup() {
            ISession s = Instance.Session;
        }

        public static void shutdown() {
            if (instance.session != null) {
                instance.session.Close();
            }
            if (instance.factory != null) {
                instance.factory.Close();
            }
        }

        private ISession session;

        public ISession Session {
            get {
                if (session == null) {
                    session = createSession();
                }
                return session;
            }
        }

        public IStatelessSession createStatelessSession() {
            return factory.OpenStatelessSession();
        }

        public ISession createSession() {
            return factory.OpenSession();
        }
    }
}
